<!-- 选择好的商品 -->
<template>
  <div class="select-pro" v-if="tableList.length > 0">
    <el-table :data="tableList" v-loading="tableLoading" ref="tableData" border fit @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="序号" type="index" width="70" align="center"></el-table-column>
      <el-table-column prop="pic" label="商品图片" align="center">
        <template slot-scope="scope">
          <el-image :src="scope.row.pic || ''" style="width: 50px; height: 50px" fit="fit" :preview-src-list="scope.row.pic ? [scope.row.pic] : []"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" min-width="130" align="center"></el-table-column>
      <el-table-column label="商品规格" prop="productStyleStr" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.productStyle === 1">单规格</span>
          <span v-if="scope.row.productStyle === 2" @click="handleShowSelectSpec(scope.row, scope.$index)" style="font-size: 12px;margin: 0;"
                :class="['click-ele', {'disabled': selectSpecShow}]">
            <i v-if="selectSpecShow" class="el-icon-loading"></i>
            选择规格</span>
        </template>
      </el-table-column>
      <el-table-column label="原积分" prop="originUsePointLimit" align="center"></el-table-column>
      <el-table-column label="原价格" prop="originPrice" align="center"></el-table-column>

      <el-table-column label="活动积分" prop="price" align="center" width="120px">
        <template slot-scope="scope">
          <input v-model="scope.row.usePointLimit" v-if="scope.row.productStyle === 1" :disabled="payWay === '2'"
                 :class="['select-input', {'error': scope.row.integralError}, {'disabled': payWay === '2'}]" @change="handleInputChange($event, 1, scope.$index, scope.row)" />
          <span v-else>{{scope.row.activityUsePointLimit || scope.row.originUsePointLimit}}</span>
          <div class="error-tips" v-if="scope.row.integralError">积分格式错误</div>
        </template>
      </el-table-column>

      <el-table-column label="活动价格" prop="usePointLimit" align="center" width="120px">
        <template slot-scope="scope">
          <input v-model="scope.row.price" v-if="scope.row.productStyle === 1" :disabled="payWay === '1'" :class="['select-input', {'error': scope.row.priceError}, {'disabled': payWay === '1'}]"
                 @change="handleInputChange($event, 2, scope.$index, scope.row)" />
          <span v-else>{{scope.row.activityPrice || scope.row.originPrice}}</span>
          <div class="error-tips" v-if="scope.row.priceError">价格格式错误</div>
        </template>
      </el-table-column>

      <el-table-column label="库存" prop="stock" align="center"></el-table-column>
      <el-table-column label="排序" prop="sort" align="center" width="120px">
        <template slot-scope="scope">
          <input v-model="scope.row.sort" @change="handleInputChange($event, 3, scope.$index, scope.row)" :disabled="activitySort === 'def'"
                 :class="['select-input', {'error': scope.row.sortError}, {'disabled': activitySort === 'def'}]" />
          <div class="error-tips" v-if="scope.row.sortError">排序格式错误</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="usePointLimit" align="center">
        <template slot-scope="scope">
          <span class="click-ele danger" @click="handleRemove(scope.row, scope.$index)">删除</span>
        </template>
      </el-table-column>
    </el-table>

    <div class="set-spec-opr">
      <span>已选规格&nbsp;&nbsp; {{selectionList.length}}</span>&nbsp;
      <span v-if="selectionList.length > 0" @click="handleRemove('')" class="click-ele danger">删除</span>
      <span v-if="selectionList.length <= 0" class="click-ele disabled">删除</span>
      <span>批量设置(只批量设置单规格商品)：
        <span :class="['click-ele', {'disabled': v.payWay === payWay }]" v-for="(v , index) in batchList" :key="index"
              @click="handleBatchSet(v)">{{v.name}}</span>
      </span>
    </div>

    <!-- 选择规格 -->
    <selectSpec v-if="selectSpecShow" :modalShow.sync="selectSpecShow" @upSendData="getSelectSpec"></selectSpec>
  </div>
</template>

<script>
import { GetProductInfo } from '@/api/onlineMan'
import selectSpec from './selectSpec'
export default {
  name: 'SelectedPro',
  components: { selectSpec },
  data () {
    return {
      tableList: [],
      tableLoading: false,
      totalCount: 0,
      selectionList: [],
      selectionIdsList: [],
      selectionIdsObj: {},
      selectSpecShow: false,
      currId: '',
      currIndex: ''
    }
  },
  props: {
    options: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    'selectedProductList': function (val) {
      this.tableList = val
    },
    'payWay': function (val) {
      this.handlePayWay(val)
    },
    'activitySort': function (val) {
      this.handleSort(val)
    }
  },
  computed: {
    selectedProductList () {
      return this.$store.state.selectProduct.selectedProductList
    },
    batchList () {
      return this.$store.state.selectProduct.batchList
    },
    payWay () {
      return this.$store.state.selectProduct.payWay
    },
    activitySort () {
      return this.$store.state.selectProduct.sort
    }
  },
  mounted () {
    this.tableList = this.selectedProductList
    this.handlePayWay()
  },
  methods: {
    handleSort (val) {
      val = val || this.activitySort
      this.tableList.forEach(e => {
        // def 系统默认排序 zdy 自定义排序
        if (val === 'def') {
          e.sort = ''
        }
      })
    },
    /* 处理支付方式 */
    handlePayWay (val) {
      val = val || this.payWay
      this.tableList.forEach(e => {
        // 活动 支付方式 0 积分+金额 1 积分 2 金额
        if (val === '0') {
          e.price = e.originPrice
          e.usePointLimit = e.originUsePointLimit
        }
        if (val === '1') {
          e.price = '0'
          e.usePointLimit = e.originUsePointLimit
        }
        if (val === '2') {
          e.price = e.originPrice
          e.usePointLimit = '0'
        }
      })
    },
    handleSelectionChange (selection) {
      this.selectionList = selection
      this.selectionIdsObj = {}
      selection.forEach(e => {
        this.selectionIdsObj[e.productId] = e.productId
      })
    },

    /* 打开 选择规格弹窗 */
    handleShowSelectSpec (row, index) {
      this.currId = row.productId || row.id || ''
      if (!this.currId) {
        this.$message.warning('商品数据错误[未发现商品id]！')
        return
      }
      this.currIndex = index === 0 ? 0 : index
      this.selectSpecShow = true
      const selectSkus = row.selectSkus || []
      if (!row.stocks || row.stocks.length <= 0) {
        // 没有获取商品的规格 详情中去获取
        this.getDetail(index, selectSkus)
      } else {
        let datas = {
          skus: row.skus,
          stocks: row.stocks
        }
        datas.stocks.forEach(e => {
          e.selected = selectSkus[e.id]
        })
        this.$store.dispatch('setProductSpecList', datas)
      }
    },

    getDetail (index, selectSkus) {
      const id = this.currId
      GetProductInfo(id).then(res => {
        const data = res.data || {}
        this.tableList[index].skus = data.skus || []
        this.tableList[index].stocks = data.stocks || []
        const datas = {
          skus: data.skus,
          stocks: data.stocks,
          selectSkus: selectSkus
        }
        this.dispatchSpecList(datas)
      }).catch(() => {
      })
    },

    // 传递选择的规格数据
    dispatchSpecList (data) {
      let selectSkusObj = data.selectSkus || null
      if (!selectSkusObj) {
        const datas = {
          skus: data.skus,
          stocks: data.stocks
        }
        this.$store.dispatch('setProductSpecList', datas)
      } else {
        let datas = { skus: data.skus }
        let stocks = JSON.parse(JSON.stringify(data.stocks))
        stocks.forEach(e => {
          e.originPrice = e.originPrice || e.price || 0
          e.originUsePointLimit = e.originUsePointLimit || e.usePointLimit || 0
          // selectSkusObj 存在 e.id 赋值 勾选

          if (selectSkusObj[e.id]) {
            e.selected = true
            e.price = selectSkusObj[e.id].price ? selectSkusObj[e.id].price : '0'
            e.usePointLimit = selectSkusObj[e.id].usePointLimit ? selectSkusObj[e.id].usePointLimit : '0'
            // e.sort = selectSkusObj[e.id].sort ? selectSkusObj[e.id].sort : '0'
          }
        })
        datas.stocks = stocks
        this.$store.dispatch('setProductSpecList', datas)
      }
    },

    // 得到选中的规格
    getSelectSpec (data) {
      const index = this.currIndex
      let info = JSON.parse(JSON.stringify(this.tableList[index]))
      info.stocks = data
      info.activityPrice = this.countMaxMin('price', data).range
      info.activityUsePointLimit = this.countMaxMin('usePointLimit', data).range

      this.$nextTick(e => {
        this.$set(this.tableList, index, info)
      })
      this.assginSelectProductData()
    },

    // 计算最小-最大数值
    countMaxMin (type, data) {
      const array = data.filter(e => e.selected)
      if (!array || array.length <= 0) {
        return
      }

      // 假设第一个为最大、最小的
      const firstVal = array[0][type] ? Number(array[0][type]) : 0
      let result = {
        min: firstVal,
        max: firstVal,
        range: ''
      }
      for (let index = 0; index < array.length; index++) {
        const currVal = Number(array[index][type])
        if (currVal > result.max) {
          result.max = currVal
        }
        if (currVal < result.min) {
          result.min = currVal
        }
      }
      result.range = (result.min ? result.min.toString() : '0') + '-' + (result.max ? result.max.toString() : '0')
      return result
    },

    /* 删除商品 */
    handleRemove (row, index) {
      if (this.tableList.length <= 1) {
        this.$message.warning('选中的商品数据仅剩一条，不可再删除！')
        return
      }
      if (!row && Object.keys(this.selectionIdsObj).length === this.tableList.length) {
        this.$message.warning('不可全部删除添加的商品数据！')
        return
      }
      this.$confirm(`确定要删除${row ? '该' : '选中的'}数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row) {
          this.tableList.splice(index, 1)
        } else {
          // 只留下 未选中的数据
          let list = JSON.parse(JSON.stringify(this.tableList))
          this.tableList = list.filter(e => {
            // selectionIdsObj 不包含 保留 包含 踢出
            if (!this.selectionIdsObj[e.productId]) {
              return e
            }
          })
        }
        this.assginSelectProductData()
      }).catch(() => { })
    },

    handleSortInputChange (val, index, row) {
      const sortNum = val.target.value || ''
      const sortReg = /^([1-9]\d*|[0]{1,1})$/ // 含零的正整数正则
      if (!sortReg.test(sortNum) || sortNum.length >= 5) {
        this.$nextTick(() => {
          row.sortError = true
          this.$set(this.tableList, index, row)
        })
      } else {
        this.$nextTick(() => {
          row.sortError = false
          this.$set(this.tableList, index, row)
        })
        this.assginSelectProductData()
      }
    },
    handleIntegralInputChange (val, index, row) { },
    handlePriceInputChange (val, index, row) { },
    // 1积分 2价格 3排序改变
    handleInputChange (val, type, index, row) {
      const value = val.target.value || ''
      const priceReg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/ // 含零的正整数正则 小数两位
      const sortReg = /^([1-9]\d*|[0]{1,1})$/ // 含零的正整数正则
      let reg = ''
      let len = 5
      if (type === 1) {
        reg = sortReg
        len = 8
      }
      if (type === 2) {
        reg = priceReg
        len = 8
      }
      if (type === 3) {
        reg = sortReg
        len = 5
      }
      if (!reg.test(value) || value.length >= len) {
        this.$nextTick(() => {
          if (type === 1) row.integralError = true
          if (type === 2) row.priceError = true
          if (type === 3) row.sortError = true
          this.$set(this.tableList, index, row)
        })
      } else {
        this.$nextTick(() => {
          if (type === 1) row.integralError = false
          if (type === 2) row.priceError = false
          if (type === 3) row.sortError = false
          this.$set(this.tableList, index, row)
        })
        this.assginSelectProductData()
      }
    },

    handleBatchSet (row) {
      if (row.payWay === this.payWay) {
        return
      }
      if (this.selectionList.length <= 0) {
        this.$message.warning('请选择需要批量设置的数据！')
        return
      }

      this.$prompt('', `批量设置${row.name}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: row.reg,
        inputErrorMessage: row.name + '格式不正确'
      }).then(({ value }) => {
        this.setVal(row.key, value)
      }).catch(() => { })
    },
    setVal (key, value) {
      this.tableLoading = true
      setTimeout(() => {
        this.tableList.forEach(e => {
          if (e.productStyle !== 2 && this.selectionIdsObj[e.productId]) {
            e[key] = value
          }
        })
        this.tableLoading = false
        this.assginSelectProductData()
      }, 100)
    },

    assginSelectProductData () {
      let data = this.tableList || []
      this.$store.dispatch('assignSelectedProductList', data)
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
